<template>
  <div>
    <page-view>

      <template #tabBar>
        <el-tabs v-model="activeName" @tab-click="handleClick">
          <el-tab-pane label="本地表" name="first">

          </el-tab-pane>
          <el-tab-pane label="自定义表" name="second">

          </el-tab-pane>
        </el-tabs>
      </template>
      <template #option v-if="activeName == 'second'">
        <div class="btn-box">
          <el-button type="primary" @click="showAddFrom">新增</el-button>
        </div>
      </template>

      <template #form>
        <SearchForm :data-form="formInline" labelWidth="120px" @on-search="onSearch" @onReset="onSearch" style="margin: 0px"
          v-if="activeName == 'first'">
          <el-form-item prop="name">
            <el-select v-model="formInline.name" filterable clearable placeholder="请选择本地数据源表名称">
              <el-option v-for="item in options1" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </SearchForm>
        <SearchForm :data-form="formInline2" labelWidth="120px" @on-search="onSearch" @onReset="onSearch" style="margin: 0px"
          v-if="activeName == 'second'">
          <el-form-item prop="sourceName">
            <el-select v-model="formInline2.sourceName" filterable clearable placeholder="请选择自定义表数据源表名称">
              <el-option v-for="item in options2" :key="item.docName" :label="item.docName" :value="item.docName" />
            </el-select>
          </el-form-item>
        </SearchForm>
      </template>
      <template #table="tableScope">
        <PubilcTable v-if="activeName == 'first'" :tableHeight="tableScope.tableHeight" :showPageSize="false"
          :table-data="tableData1" :list-config="columns1" :page-data="pageData" @on-action="onAction" />
        <PubilcTable v-if="activeName == 'second'" :tableHeight="tableScope.tableHeight" :table-data="tableData2"
          :list-config="columns2" :translateTextDeal="translateTextDeal" :page-data="pageData" @on-action="onAction" />
      </template>
    </page-view>


    <eForm :dialog-visible="dialogVisible" :is-add="isAdd" :formData="formData" @on-submit="formSubmit"
      @handle-close="handleClose" />
    <associationForm :dialog-visible="dialogVisible2" :formData="formData2" :oldData="oldData2" @on-submit="onSearch"
      @handle-close="handleClose" v-if="dialogVisible2" :localName="localName" />
  </div>
</template>
<script  setup>
import api from '@/api/index'
import { onMounted, reactive, ref } from 'vue'
import eForm from './components/addForm.vue'
import associationForm from './components/associationForm.vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { docTypeOption } from './components/config'
import { statusText } from '@/util/index'

let router = useRouter();
const activeName = ref('second')
const formInline = reactive({})
const formInline2 = reactive({})
const dialogVisible = ref(false)
const dialogVisible2 = ref(false)
const isAdd = ref('add')
const pageData = reactive({
  pageNum: 1,
  pageSize: 10,
  total: 0
})
const formData = ref({})
const formData2 = ref([])
const options1 = ref([])
const options2 = ref([])
const localName = ref(null)
const tableData1 = ref([])
const tableData2 = ref([])
const oldData2 = ref([])

const OPERTATE1 = [
  { alias: 'association', label: '关联外部数据' },
]
const OPERTATE2 = [
  { alias: 'edit', label: '编辑' },
  { alias: 'addDataValue', label: '添加值' },
  { alias: 'association', label: '关联外部数据' },
  { alias: 'del', label: '删除' }
]

const columns1 = [
  { alias: 'name', label: '数据源表名称' },
  { alias: 'type', label: '数据源表类型' },
  { alias: 'code', label: '数据源表code' },
  { label: '操作', listArr: OPERTATE1, width: '280px', fixed: 'right', type: 'action' }
]

const columns2 = [
  { alias: 'docName', label: '数据源表名称' },
  { alias: 'docType', label: '数据源表类型', type: 'translateText' },
  { alias: 'docCode', label: '数据源表code' },
  { label: '操作', listArr: OPERTATE2, width: '280px', fixed: 'right', type: 'action' }
]

onMounted(() => {
  getoptions1()
  getoptions2()
  onSearch()
})
const getoptions1 = () => {
  api.dataMaintenance.getLocalTable().then((res) => {
    options1.value = res || []
  })
}
const getoptions2 = () => {
  api.dataMaintenance.getAllTable().then((res) => {
    options2.value = res || []
  })
}
const handleClick = (tab, event) => {
  onSearch()
}
const onSearch = () => {
  if (activeName.value === 'first') {
    const data = options1.value
    if (formInline.name) {
      const newData = data.filter(item => item === formInline.name);
      tableData1.value = newData.map((item) => {
        return {
          name: item,
          type: '本地表',
          code: item,
        }
      })
    } else {
      api.dataMaintenance.getLocalTable().then((res) => {
        tableData1.value = res || []
        tableData1.value = tableData1.value.map((item) => {
          return {
            name: item,
            type: '本地表',
            code: item,
          }
        })
      })
    }
  } else {
    const params = { ...formInline2, ...pageData, type: 0 }
    api.dataMaintenance.getConditionList(params).then((res) => {
      tableData2.value = res.list || []
      pageData.total = res.total || 0
    })
  }
}
const deleteRow = (val) => {
  ElMessageBox.confirm('确定删除此数据源表吗？删除后将不可恢复。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const id = val.id
    api.dataMaintenance.deleteTable(id).then((res) => {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      });
      onSearch()
    })
  })
}
const editRow = (row) => {
    localStorage.setItem('addDataParams', JSON.stringify(row));
    router.push({
        name: 'addData'
    })
}
const associationRow = (row) => {
  console.log(row)
  const id = row.id
  const params = {
    tableName: row.name
  }
  if (activeName.value === 'first') {
    // 本地表
    localName.value = row.name
    api.dataMaintenance.getTableColumnsDetail(params).then((res) => {
      if (res) formData2.value = res
      // 查询本地表数据
      localityTableList(params, res)
      dialogVisible2.value = true
    })
  } else {
    let metaData = JSON.parse(row.metaData)
    localName.value = null
    let obj = outDatapackage(metaData, id)
    // 自定义表
    api.dataMaintenance.getDetailBySourceId(id).then((res) => {
      if (res) {
        formData2.value = res
      } else {

        formData2.value = [obj]
      }
      oldData2.value = JSON.parse(JSON.stringify(obj))
      dialogVisible2.value = true
    })

  }
}

// 数据组装
const outDatapackage = (metaData, id, field = 'fieldCode') => {
  if (!metaData) {
    ElMessage({
      type: 'error',
      message: '请先配置表字段!'
    });
    return
  }
  let fieldDataMappingVOList = []
  metaData.forEach(item => {
    fieldDataMappingVOList.push(
      {
        attrCode: item[field],//左边字段
        mappedForm: '',//右边字段
      }
    )
  })

  return {
    fieldDataMappingVOList,
    matchCode: null,
    sourceId: id
  }
}

// 获取本地表外部数据源左边数据
const localityTableList = (params, data) => {
  api.dataMaintenance.getTableColumnsByTableName(params).then((res) => {
    console.log(res, 'res')
    let obj = outDatapackage(res, null, 'columnName')
    oldData2.value = JSON.parse(JSON.stringify(obj))

    if (!data) formData2.value = [obj]

    console.log(formData2.value, obj, id)

  })
}

const addDataValueRow = (row) => {
    let detailDataValue = {}
    if (row) {
        detailDataValue.sourceId = row.id
        if (row.metaData && row.metaData !== 'null') {
            const searchData = [...JSON.parse(row.metaData)]
            searchData.forEach((item) => {
                item.value = item.fieldCode
                item.label = item.fieldName
            })
            const columnsData = [...JSON.parse(row.metaData)]
            columnsData.forEach((item) => {
                item.alias = item.fieldCode
                item.label = item.fieldName
            })
            detailDataValue.searchOptions = searchData
            detailDataValue.columnsOptions = columnsData
        } else {
            detailDataValue.searchOptions = []
            detailDataValue.columnsOptions = []
        }
    }
    localStorage.setItem('detailDataValue', JSON.stringify(detailDataValue));
    router.push({
        name: 'addDataValue'
    })
}
const onAction = ([item, row]) => {
  const obj = {
    'del': deleteRow,
    'edit': editRow,
    'addDataValue': addDataValueRow,
    'association': associationRow,
    'pageNum': onSearch,
    'pageSize': onSearch
  }
  if (typeof item === 'string') {
    pageData[item] = row
    if (item === 'size') pageData.page = 1
    obj[item]()
  } else {
    obj[item.alias](row)
  }
}

const showAddFrom = () => {
  dialogVisible.value = true
  isAdd.value = 'add'
}
const formSubmit = (val) => {
  const params = { ...val }
  api.dataMaintenance.createTable(params).then((res) => {
    ElMessage({
      type: 'success',
      message: '新增成功!'
    });
    onSearch()
  })
}

const handleClose = val => {
  dialogVisible.value = val
  dialogVisible2.value = val
}

const translateTextDeal = (item, val) => {
  if (item.alias === 'docType') {
    return statusText(docTypeOption, val)
  }
}
</script>

<style lang="scss" scoped>
.demo-tabs {
  margin: 20px;
}

.demo-tabs>.el-tabs__content {
  padding: 32px;
  background-color: #f4f5f7;
  color: #6b778c;
  font-size: 32px;
  font-weight: 600;
}

.clearfix {
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
  margin-bottom: 10px;

  &:after {
    visibility: hidden;
    display: block;
    font-size: 0;
    content: " ";
    clear: both;
    height: 0;
  }

  .role-span {
    font-weight: 700;
    color: #303133;
    font-size: 15px;
  }
}

.fixButtom {
  float: right;
}
</style>
